package com.smarthealthring.mm.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.smarthealthring.mm.App;
import com.smarthealthring.mm.R;
import com.smarthealthring.mm.base.BaseActivity;
import com.smarthealthring.mm.base.IPresenter;
import com.smarthealthring.mm.ble.RtEvent;
import com.smarthealthring.mm.event.FinishHomeEvent;
import com.smarthealthring.mm.ui.fragment.HealthyFragment;
import com.smarthealthring.mm.ui.fragment.MineFragment;
import com.smarthealthring.mm.ui.fragment.OneCardFragment;
import com.smarthealthring.mm.ui.fragment.SecurityFragment;
import com.smarthealthring.mm.ui.fragment.SportsFragment;
import com.smarthealthring.mm.utils.RxBus;
import com.smarthealthring.mm.utils.RxBusBaseMessage;
import com.smarthealthring.mm.utils.RxUtil;
import com.smarthealthring.mm.utils.ToastUtil;
import com.smarthealthring.mm.widgets.bottombar.BottomBar;
import com.smarthealthring.mm.widgets.bottombar.BottomBarTab;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.functions.Consumer;

/**
 * Created by bilibili on 2018/4/1.
 */

public class HomeActivity extends BaseActivity {

    @BindView(R.id.fl_content)
    FrameLayout mFrameLayout;
    @BindView(R.id.tab)
    BottomBar mBottomBar;
    private FragmentManager mFragmentManager;

    private HealthyFragment mHealthyFragment;
    private SportsFragment mSportsFragment;
    private SecurityFragment mSecurityFragment;
    private OneCardFragment mOneCardFragment;
    private MineFragment mMineFragment;
    private List<Fragment> mFragmentList;

    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;

    @Override
    protected void initComToolBar() {
    }

    @Override
    protected int getLayout() {
        return R.layout.act_home;
    }

    @Override
    protected void initEventAndData(Bundle savedInstanceState) {
        //首页初始化蓝牙配置
        BleManager.getInstance().init(App.getInstance());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 5000)
                .setOperateTimeout(5000);

        mFragmentManager = this.getSupportFragmentManager();

        if (savedInstanceState != null) {
            mHealthyFragment = (HealthyFragment) mFragmentManager.findFragmentByTag(HealthyFragment.class.getName());
            mSportsFragment = (SportsFragment) mFragmentManager.findFragmentByTag(SportsFragment.class.getName());
            mSecurityFragment = (SecurityFragment) mFragmentManager.findFragmentByTag(SecurityFragment.class.getName());
            mOneCardFragment = (OneCardFragment) mFragmentManager.findFragmentByTag(OneCardFragment.class.getName());
            mMineFragment = (MineFragment) mFragmentManager.findFragmentByTag(MineFragment.class.getName());
        }

        if (mHealthyFragment == null)
            mHealthyFragment = HealthyFragment.getInstance();
        if (mSportsFragment == null)
            mSportsFragment = SportsFragment.getInstance();
        if (mSecurityFragment == null)
            mSecurityFragment = SecurityFragment.getInstance();
        if (mOneCardFragment == null)
            mOneCardFragment = OneCardFragment.getInstance();
        if (mMineFragment == null)
            mMineFragment = MineFragment.getInstance();
        mFragmentList = new ArrayList<>();
        mFragmentList.add(mHealthyFragment);
        mFragmentList.add(mSportsFragment);
        mFragmentList.add(mSecurityFragment);
        mFragmentList.add(mOneCardFragment);
        mFragmentList.add(mMineFragment);

        replaceFragment(mHealthyFragment, null);

        mBottomBar
                .addItem(new BottomBarTab(mContext, R.drawable.healthy0, "健康"))
                .addItem(new BottomBarTab(mContext, R.drawable.sport0, "运动"))
                .addItem(new BottomBarTab(mContext, R.drawable.fangwei0, "防伪"))
                .addItem(new BottomBarTab(mContext, R.drawable.yikatong0, "一卡通"))
                .addItem(new BottomBarTab(mContext, R.drawable.mine0, "我的"));

        mBottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                replaceFragment(mFragmentList.get(position), mFragmentList.get(prePosition));
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });


        mBottomBar.setCurrentItem(getIntent().getIntExtra("currentPos", 0));

        // 请求GPS
        checkPermissions();
        registerEvent();

        Log.e("life_homeact==", "onInit...");

        RxBus.getInstance().tObservable(FinishHomeEvent.class)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Consumer<FinishHomeEvent>() {
                    @Override
                    public void accept(FinishHomeEvent finishHomeEvent) throws Exception {
                        finish();
                    }
                });
    }

    @Override
    protected IPresenter createPresenter() {
        return null;
    }

    /**
     * 点击Tab切换Fragment
     */

    public void replaceFragment(Fragment showFragment, Fragment hideFragment) {
        if (showFragment == hideFragment)
            return;

        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (hideFragment != null) {
            transaction.hide(hideFragment);
        } else {
            for (Fragment fragment : mFragmentManager.getFragments()) {
                if (fragment != null && fragment != showFragment) {
                    transaction.hide(fragment);
                }
            }
        }

        if (!showFragment.isAdded()) {
            transaction.add(R.id.fl_content, showFragment, showFragment.getClass().getName());
        } else {
            transaction.show(showFragment);
        }

        transaction.commit();
    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 3000) {
                ToastUtil.shortShow("再按一次退出应用程序");
                exitTime = System.currentTimeMillis();
            } else {
                App.getInstance().exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void selectHomePage() {

        Flowable.timer(500, TimeUnit.MILLISECONDS)
                .compose(RxUtil.scheduleTnansform())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        mBottomBar.setCurrentItem(0);
                    }
                });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mBottomBar.setCurrentItem(intent.getIntExtra("currentPos", 0));
        Log.e("life_homeact==", "onNewIntent...");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleManager.getInstance().disconnectAllDevice();
        BleManager.getInstance().destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 判断蓝牙是否连接状态，未连接则连接
        // 根据设备重连连接mac

        Log.e("life_homeact==", "onResume...");
//        if (SPUtils.getInt(SPUtils.BOND_STATE, 0) == 0)
//            return;
//        if (!BleManager.getInstance().isConnected(SPUtils.getString(SPUtils.DEVICE_MAC, ""))) {
//            BdProtocol.connectWithMac(SPUtils.getString(SPUtils.DEVICE_MAC, ""));
//        }

    }

    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_LOCATION:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            onPermissionGranted(permissions[i]);
                        }
                    }
                }
                break;
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.notifyTitle)
                            .setMessage(R.string.gpsNotifyMsg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton(R.string.setting,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {

                }
                break;
        }
    }

    /**
     * 检查GPS是否开启
     */
    private void checkPermissionsGPS() {
        // 请求GPS
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }

    }

    void registerEvent() {

        RxBus.getInstance().tObservable(RtEvent.BLE_ON, RxBusBaseMessage.class)
                .subscribe(new Consumer<RxBusBaseMessage>() {
                    @Override
                    public void accept(RxBusBaseMessage rxBusBaseMessage) throws Exception {
                        Log.e("register===", "收到蓝牙打开事件...");
                        checkPermissionsGPS();
                    }
                });
    }

    /**
     * 检查蓝牙是否开启
     */
    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
            //请求BLE打开
            requstOpenBleForSult(this);
        }else {
            checkPermissionsGPS();
        }

    }

    //请求打开蓝牙
    public final static int REQUEST_ENABLE_BT = 30;

    public void requstOpenBleForSult(Activity activity) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        enableIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
    }


}
